package maintain

import (
	"context"
	"gf_blog_admin/internal/dao"
	"gf_blog_admin/internal/model"
	"gf_blog_admin/internal/service"
	"github.com/gogf/gf/v2/errors/gerror"
)

type sOptionLog struct{}

func init() {
	service.RegisterOptionLog(NewOptionLog())
}

func NewOptionLog() *sOptionLog {
	return &sOptionLog{}
}

func (s *sOptionLog) List(ctx context.Context, in *model.OptionLogListInput) (out []*model.OptionLogListItem, total int, err error) {
	var (
		cls = dao.BlSysOptionLog.Columns()
		m   = dao.BlSysOptionLog.Ctx(ctx)
	)

	if in.Username != "" {
		m = m.Where(cls.Username, in.Username)
	}
	if in.StartDate != "" && in.EndDate != "" {
		m = m.WhereBetween(cls.CreatedAt, in.StartDate, in.EndDate)
	}

	out = make([]*model.OptionLogListItem, 0)
	err = m.OrderDesc(cls.Id).
		Fields(
			cls.Id, cls.UserId, cls.IpAddress, cls.ModuleType, cls.ModuleId,
			cls.LogAction, cls.LogRemark, cls.CreatedAt,
		).
		Page(in.Page, in.PageSize).
		ScanAndCount(&out, &total, false)
	return
}

func (s *sOptionLog) Detail(ctx context.Context, id uint64) (out *model.OptionLogItem, err error) {
	err = dao.BlSysOptionLog.Ctx(ctx).Where(dao.BlSysOptionLog.Columns().Id, id).Scan(&out)
	if err != nil {
		return nil, err
	}
	if out == nil {
		return nil, gerror.New("数据不存在")
	}
	return
}
